using System;
using System.Collections.Generic;
using System.Text;

using ghostDBscript.Engine;

namespace ghostDBscript.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                string filename = args[0];
                if (!System.IO.File.Exists(filename))
                    DisplayFileNotFoundMessage(filename);
                else
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(filename);
                    string input = sr.ReadToEnd();
                    sr.Close();

                    string output = ScriptEngine.ProcessString(input);

                    if (filename.Substring(filename.Length - 5, 5).Contains("."))
                    { 
                        int fromEndLastPeriod = filename.Length - filename.LastIndexOf(".");
                        filename = filename.Substring(0, filename.Length - fromEndLastPeriod) + ".sql";
                    }
                    else
                        filename += ".sql";

                    System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, false);
                    sw.Write(output);
                    sw.Close();

                    sw.Dispose();
                    sr.Dispose();
                }
            }
            else
                DisplayNoArgsMessage();
        }

        private static void DisplayFileNotFoundMessage(string file)
        {
            System.Console.WriteLine("The file '" + file + "' was not found.");
        }

        private static void DisplayNoArgsMessage()
        {
            System.Console.WriteLine("Usage -->  ghostdbscript <ghostDBscript to process>");
        }
    }
}
